export enum EventCode {
  NODE_EVENT = "node_event",
  MTTQ = "mttq",
}
const Events = {};

/**
 * 事件key规则
 * ```javascript
 * // key=code.other
 * //node event key:
 * CreateEventKey(EventCode.NODE_EVENT, data.key, data.target.guid)
 * //mttq key:
 * CreateEventKey(EventCode.MTTQ, data.topic)
 * ```
 * @param val
 */
export function ClientMsgHandel(val) {
  const { code, msg, data } = val;
  if (code)
    if (code == EventCode.NODE_EVENT) {
      const call = Events[CreateEventKey(EventCode.NODE_EVENT, data.target.guid, data.key)];
      if (call && typeof call == "function") {
        call(data);
      }
      return;
    }
  if (code == EventCode.MTTQ) {
    const call = Events[CreateEventKey(EventCode.MTTQ, data.topic)];
    if (call && typeof call == "function") {
      call(data.message);
    }
    return;
  }
  const call = Events[code];
  if (call && typeof call == "function") {
    call(data);
  }
  return;
}

export function ClientMsgOn(key, callback) {
  Events[key] = callback;
}
export function ClientMsgOff(key) {
  delete Events[key];
}

export function CreateEventKey(...val: Array<string>) {
  return val.join(".");
}
